package com.junxonline.instant.terminal;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.github.yitter.contract.IdGeneratorOptions;
import com.github.yitter.idgen.YitIdHelper;
import com.junxonline.instant.dao.entity.model.device.Terminal;
import com.junxonline.instant.dao.mapper.device.TerminalMapper;
import lombok.extern.log4j.Log4j2;
import org.apache.dubbo.config.spring.context.annotation.EnableDubbo;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.WebApplicationType;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
import org.springframework.core.env.Environment;
import org.springframework.scheduling.annotation.EnableAsync;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.List;

@Log4j2
@EnableAsync
@EnableAspectJAutoProxy
@EnableDubbo
@MapperScan(basePackages = "com.junxonline.instant.dao.mapper.**.*")
@SpringBootApplication(scanBasePackages = {"com.junxonline.instant.terminal", "com.junxonline.instant.dao.mapper.**.*", "com.junxonline.instant.common.util.terminal", "com.junxonline.instant.common.util.common"})
public class InstantTerminalServer {

    public static void main(String[] args) {
        // 以非Web方式启动
        ConfigurableApplicationContext context = new SpringApplicationBuilder(InstantTerminalServer.class).web(WebApplicationType.NONE).run(args);
        Environment environment = context.getBean(Environment.class);
        initIdGeneratorOptions(environment);
        startApplicationOver(environment);
        resetTerminalStatus(context);
    }

    private static void initIdGeneratorOptions(Environment environment) {
        String workerId = environment.getProperty("id-generator.workerId");
        try {
            IdGeneratorOptions options = new IdGeneratorOptions(Short.parseShort(workerId));
            YitIdHelper.setIdGenerator(options);
            log.info("- 雪花漂移算法机器码初始化成功：" + workerId);
        } catch (Exception e) {
            log.error("- 请设置雪花漂移算法机器码!");
        }
    }

    private static void startApplicationOver(Environment environment) {
        String ip = "";
        try {
            ip = InetAddress.getLocalHost().getHostAddress();
        } catch (UnknownHostException e) {
            log.error("- Don't get Application host address!");
        }
        log.info("[" + environment.getProperty("spring.application.name") + "] Application running at:");
        log.info("- Local:   ws://localhost:" + environment.getProperty("netty.port") + environment.getProperty("netty.path"));
        log.info("- Network: ws://" + ip + ":" + environment.getProperty("netty.port") + environment.getProperty("netty.path"));
    }

    private static void resetTerminalStatus(ConfigurableApplicationContext context) {
        TerminalMapper terminalMapper = context.getBean(TerminalMapper.class);
        log.info("开始初始化终端状态..");
        // 查找所有非离线终端
        List<Terminal> terminalList = terminalMapper.selectList(new LambdaQueryWrapper<Terminal>().ne(Terminal::getStatus, 0).ne(Terminal::getStatus, 3));
        for (Terminal terminal : terminalList) {
            terminalMapper.updateStatusOfflineByCode(0, terminal.getCode());
        }
        log.info(terminalList.size() + "台终端状态初始化为离线");
    }

}
